package cn.elite.sqlSession;

import cn.elite.pojo.Configuration;
import cn.elite.pojo.MappedStatement;
import cn.elite.pojo.SqlCommandType;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: ZLY
 * @Date: 2020/10/6 16:42
 * @Description:
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;
    private final Executor executor;
    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.executor = new SimpleExecutor();
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception {
        return update(statementId,params);
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        MappedStatement ms = configuration.getMappedStatementMap().get(statementId);
        return executor.update(configuration,ms,params);
    }

    @Override
    public int delete(String statementId, Object... params) throws Exception {
        return update(statementId,params);
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> res = executor.query(configuration, mappedStatement, params);
        return (List<E>) res;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size()==1) {
            return (T) objects.get(0);
        }else{
            throw new RuntimeException("查询结果过多或者为空!");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) throws Exception {
        return (T) Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                //获取statementid
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId  = className+"."+methodName;

                //获取type
                SqlCommandType sqlCommandType = configuration.getMappedStatementMap().get(statementId).getSqlCommandType();

                Object result;
                //根据type判定SQL类型
                switch (sqlCommandType){
                    case INSERT:{
                        result = insert(statementId,args);
                        break;
                    }
                    case UPDATE:{
                        result = update(statementId,args);
                        break;
                    }
                    case DELETE:{
                        result = delete(statementId,args);
                        break;
                    }
                    case SELECT:{
                        //参数2.param:args
                        //返回值类型
                        Type genericReturnType = method.getGenericReturnType();
                        //返回值类型是否是参数化类型,来判断是查询一个,还是查询所有
                        //参数化类型:可以理解为有<>的类型比如: List<xx>,Map<String,String> 参数化类型,而List,Map不是
                        if(genericReturnType instanceof ParameterizedType){
                            List<Object> objects = selectList(statementId,args);
                            return objects;
                        }
                        result = selectOne(statementId,args);
                        break;
                    }
                    default:
                        throw new RuntimeException("Unknown execution method for: " + method.getName());
                }


                if (result == null && method.getReturnType().isPrimitive() && method.getReturnType()!=void.class) {
                    throw new RuntimeException("Mapper method '" + method.getName()
                            + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
                }
                return result;
            }
        });
    }
}
